const {ccclass, property} = cc._decorator;

interface DropCallback {
    (index: number):void
}

@ccclass
export default class DropList extends cc.Component {

    @property(cc.Node)
    rootItem: cc.Node = null;

    @property(cc.Prefab)
    itemPrefab: cc.Prefab = null;

    @property(cc.ScrollView)
    scrollview: cc.ScrollView = null;

    _callback: DropCallback = null;

    _array: any = [];

    _select: any = null;

    onLoad () {

    }

    setData(array, select) {
        if (select == null) {
            select = 0;
        }
        this._array = array;
        this._select = select;
        this.rootItem.getComponent(this.rootItem.name).setItem(array[select]);
        this.scrollview.content.destroyAllChildren();
        for (let index = 0; index < array.length; index++) {
            const data = array[index];
            let node = cc.instantiate(this.itemPrefab);
            this.scrollview.content.addChild(node);
            node.getComponent(this.rootItem.name).setItem(data);
            let button = node.getComponent(cc.Button);
            var eventHandler = new cc.Component.EventHandler();
            eventHandler.target = this.node;
            eventHandler.component = "DropList";
            eventHandler.handler = "onBtnClickItem";
            eventHandler.customEventData = index + '';
            button.clickEvents.push(eventHandler);
        }

        this.scrollview.node.active = false;
    }

    setSelectCallback (callback: DropCallback) {
        this._callback = callback;
    }

    getSelectData () {
        return this._array[this._select];
    }

    setSelectData (data) {
        for (let index = 0; index < this._array.length; index++) {
            const item = this._array[index];
            if (item == data) {
                this._select = index;
                this.rootItem.getComponent(this.rootItem.name).setItem(item);
            }
        }
    }

    getSelectIndex () {
        return this._select;
    }

    setSelectIndex (index) {
        this._select = index;
        let data = this._array[index];
        this.rootItem.getComponent(this.rootItem.name).setItem(data);
    }

    onBtnClickRoot () {
        this.scrollview.node.active = !this.scrollview.node.active;
    }

    onBtnClickItem (event, param) {
        let select = parseInt(param);
        this._select = select;
        this.rootItem.getComponent(this.rootItem.name).setItem(this._array[this._select]);
        this.scrollview.node.active = false;
        if (this._callback) {
            this._callback(select);
        }
    }

    // update (dt) {},
}